from flask import render_template, request, jsonify
from . import detection_bp
from ..utils.stats import record_api_call
import requests
import base64
import json

# 百度云API配置
API_KEY = 'ZWsM40uWHibmA6hu4nct354X'
SECRET_KEY = 'dmJoOzQLISTBLooGcnxNsYaetBpfove0'

def get_access_token():
    """获取百度AI平台的access_token"""
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    response = requests.post(url, params=params)
    if response:
        return response.json().get("access_token")
    return None

@detection_bp.route('/')
def index():
    return render_template('modules/object_detection.html')

@detection_bp.route('/process', methods=['POST'])
def process():
    # 记录API调用
    record_api_call('detection')
    
    if 'image' not in request.files:
        return jsonify({'success': False, 'message': '需要提供图片文件'})
    
    try:
        file = request.files['image']
        if file.filename == '':
            return jsonify({'success': False, 'message': '没有选择文件'})
        
        # 读取图片并转为base64
        image = file.read()
        image_base64 = base64.b64encode(image).decode('utf-8')
        
        # 获取with_face参数
        with_face = request.form.get('with_face', '1')
        
        # 构建请求参数
        params = {
            "image": image_base64,
            "with_face": with_face
        }
        
        # 获取access_token
        access_token = get_access_token()
        if not access_token:
            return jsonify({
                'success': False,
                'message': '获取access_token失败'
            })
        
        # 调用图像单主体检测接口
        request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/object_detect"
        request_url = f"{request_url}?access_token={access_token}"
        
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        
        if response:
            result = response.json()
            if 'error_code' in result:
                return jsonify({
                    'success': False,
                    'message': f"API错误: {result.get('error_msg', '未知错误')}"
                })
            
            return jsonify({
                'success': True,
                'result': result
            })
        else:
            return jsonify({
                'success': False,
                'message': 'API请求失败'
            })
            
    except Exception as e:
        print(f"Error processing image: {str(e)}")
        return jsonify({
            'success': False,
            'message': '处理图片时发生错误'
        }) 